<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;
use fast\Random;
/**
 * 家长列表
 */
class Parents extends Backend
{

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {

            // 获取请求参数
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->where('type', 3)
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 返回标准JSON格式
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];
            return json($result);
        }

        // 非AJAX请求返回视图
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');

             if (empty($data)) {
                $this->error('没有提交数据');
            }

            $email = $this->model->where('email', $data['email'])->find();
            if ($email) {
                $this->error('该邮箱已存在');
            }

            $mobile = $this->model->where('mobile', $data['mobile'])->find();
            if ($mobile) {
                $this->error('该手机号已存在');
            }

            $data['type'] = 3;
            $data['salt'] = Random::alnum();
            $data['password'] = $this->getEncryptPassword($data['password'], $data['salt']);

            $this->model->save($data);

        }
        return parent::add();
    }

    /**
    * 删除
    * @param $ids
    */
    public function del($ids = null)
    {
        if ($ids) {
            $rows = $this->model->where('id', 'in', $ids)->delete();
            if ($rows) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('请选择要删除的记录');
    }

    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
}